library drop_down;

import 'dart:math';

import 'package:flutter/material.dart';

import '../../../utils/util.dart';
import 'index.dart';

export './state.dart';
export './controller.dart';
export './bindings.dart';
export './view.dart';

EdgeInsets getDialogFrame(
  GlobalKey key, {
  double? width,
}) {
  var robj = key.currentContext?.findRenderObject() as RenderBox?;
  if (robj == null) {
    return EdgeInsets.zero;
  }
  var w = width ?? robj.size.width;

  var offset = robj.localToGlobal(Offset(0, robj.size.height));

  var left = offset.dx;
  if (left < TopConfig.outerhHorizontalPadding) {
    left = max(0, min(left, 1.sw - w));
  }

  var top = offset.dy;
  var bottom = 0.0;
  if (offset.dy > Get.height / 3 * 2) {
    bottom = Get.height - top + robj.size.height;
    top = 0;
  }
  return EdgeInsets.fromLTRB(left, top, w, bottom);
}

class DropDown {
  static bool get isShow {
    return Get.isRegistered<DropDownController>();
  }

  static void dismiss() {
    if (isShow) {
      Get.back();
    }
  }

  ///list child 二选一
  static Future<int?> show({
    required GlobalKey key,
    String? initialVal,
    List<String>? list,
    Widget? child,
    List<Widget>? prefixList,
    double? width,
    MainAxisAlignment alignment = MainAxisAlignment.start,
  }) async {
    dismiss();
    var frame = getDialogFrame(key, width: width);

    return Get.to(
      () => const DropDownPage(),
      arguments: DropDownModel(
        list: list,
        frame: frame,
        initialVal: initialVal,
        prefixList: prefixList,
        alignment: alignment,
        child: child,
      ),
      binding: DropDownBinding(),
      transition: Transition.fadeIn,
      fullscreenDialog: true,
      popGesture: false,
      opaque: false,
    );
  }
}
